package com.gy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.result.Papers;
import com.gy.entity.result.Report;
import com.gy.mapper.ReportMapper;
import com.gy.query.ReportQuery;
import com.gy.result.Result;
import com.gy.service.ReportService;
import com.gy.service.UserService;
import com.gy.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report> implements ReportService {
    @Autowired
    private UploadController uploadController;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private UserService userService;
    /**
     * 分页查询报道信息
     * @param reportQuery
     * @return
     */
    @Override
    public Result<PageVO<Report>> getReportPage(ReportQuery reportQuery) {
        Long userId = UserHolder.getUser().getUserId();

        Page<Report> page = Page.of(reportQuery.getPageNo(), reportQuery.getPageSize());

        // 排序条件
        if (!reportQuery.getSortBy().isEmpty() || reportQuery.getIsAsc() != null) {
            page.addOrder(new OrderItem(reportQuery.getSortBy(), reportQuery.getIsAsc()));
        } else {
            // 为空，默认按照报道时间排序
            page.addOrder(new OrderItem("report_time", false));
        }

        // 构建查询条件
        LambdaQueryChainWrapper<Report> queryWrapper = lambdaQuery().select()
                .eq(userId != null, Report::getUserId, userId);

        // 仅在开始日期和结束日期不为空且有效时添加 between 条件
        if (reportQuery.getStartDate() != null && reportQuery.getEndDate() != null) {
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(reportQuery.getStartDate());
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(reportQuery.getEndDate());
                queryWrapper.between(Report::getReportTime, startDate, endDate);
            } catch (ParseException e) {
                // 处理日期解析错误
                System.err.println("Invalid date format: " + e.getMessage());
            }
        }

        // 执行分页查询
        Page<Report> p = queryWrapper.page(page);

        // 封装VO结果
        PageVO<Report> vo = new PageVO<>();
        vo.setTotal(p.getTotal());
        vo.setPages(p.getPages());
        List<Report> records = p.getRecords();
        if (CollUtil.isEmpty(records)) {
            vo.setList(Collections.emptyList());
        } else {
            vo.setList(records);
        }
        return Result.success(vo);
    }

    /**
     * 根据id主键删除新闻报道
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result removeReport(Long id) {
        Report report = getById(id);
        if (report == null) {
            return Result.error("新闻报道未找到");
        }

        String pdfPath = report.getPdfPath();

        // 检查 pdfPath 是否为空
        if (pdfPath != null && !pdfPath.isEmpty()) {
            try {
                uploadController.deleteFile(pdfPath);
            } catch (Exception e) {
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("pdfPath 为空，无需删除文件");
        }

        boolean removed = removeById(id);
        if (!removed) {
            return Result.error("删除新闻报道失败");
        }
        userService.decrementUserReportCount();
        return Result.success("新闻报道删除成功");
    }

    @Override
    public Report getReportById(Long id) {
        if (id==null) {
            return null;
        }
        return reportMapper.selectReportById(id);
    }

    @Override
    public Result updateReport(Report report) {
        // 参数验证
        if (report == null) {
            return Result.error("报告信息不能为空");
        }
        if (report.getId() == null) {
            return Result.error("报告ID不能为空");
        }

        try {
            int affectedRows = reportMapper.updateReport(report);
            if (affectedRows > 0) {
                return Result.success(report);
            } else {
                return Result.error("未找到对应的报告信息进行更新");
            }
        } catch (Exception e) {
            // 记录日志
            log.error("更新报告信息时发生异常", e);
            return Result.error("更新报告信息失败");
        }
    }

    @Override
    @Transactional
    public Result saveReport(Report report) {
        if (report == null) {
            log.warn("传入的报告对象为空");
            return Result.error("报告对象不能为空");
        }
        try {
            // 设置用户 ID
            report.setUserId(UserHolder.getUser().getUserId());

            boolean save = reportMapper.saveReport(report);
            if (!save) {
                return Result.error("新增失败");
            }
            userService.incrementUserReportCount();

            return Result.success("新增成功");
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存报告时发生异常", e);
            return Result.error("系统错误，请稍后再试");
        }
    }

    @Override
    public Result getReportByIds(Long[] ids) {
        if (ids != null && ids.length > 0) {
            List<Report> reportList = reportMapper.selectReportBatchIds(Arrays.asList(ids));
            return Result.success(reportList);
        }
        return null;
    }


}
